﻿using System;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using YXChatApiService.Application;

namespace YXChatApiService.Filters
{
    public class ResultDataFilter : ActionFilterAttribute
    {
        /// <summary>
        /// action方法执行之前调用
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// action方法执行之后调用
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            ResultDto<object> result = new ResultDto<Object>();
            if (context.Exception != null)
            {
                result.Success = false;
                result.Msg = context.Exception.Message;
            }
            else
            {
                result.Success = true;
                // 取得由 API 返回的数据
                if (context.Result is ObjectResult objectResult)
                {
                    result.Data = objectResult.Value;
                }
            }

            context.Result = new ObjectResult(result);
            base.OnActionExecuted(context);
        }
    }
}